<template>
    <div>
        <el-card>
            <!-- 查询表单 -->
            <el-form :inline="true">
                <el-form-item label="版本号">
                    <el-input v-model="query.version" @keyup.enter.native="fetchList" clearable
                        placeholder="支持1.2.3格式" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchList">查询</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>

            <div style="margin-bottom:8px;text-align:right">
                <el-button type="primary" @click="openDialog()">新增配置</el-button>
            </div>

            <el-table :data="list" :loading="loading" border>
                <el-table-column prop="pk" align="center" label="环境" width="120">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.pk === prodPk ? 'success' : 'danger'">
                            {{ envLabel(scope.row.pk) }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="min_version" align="center" width="160" label="最低版本" />
                <el-table-column prop="max_version" align="center" width="160" label="最高版本" />
                <el-table-column label="功能列表" align="center">
                    <template slot-scope="scope">
                        <span v-for="f in parseFeature(scope.row.feature_list)" :key="f.featureName">
                            <el-tag style="margin:2px">{{ featureNameLabel(f.featureName) }}</el-tag>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="updated_at" align="center" label="修改时间" width="200" />
                <el-table-column label="操作" width="280" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="openDialog(scope.row)">编辑</el-button>
                        <el-button size="mini" v-if="scope.row.pk === prodPk" type="danger"
                            @click="switchEnv(scope.row, devPk)">
                            切换开发
                        </el-button>
                        <el-button size="mini" v-if="scope.row.pk === devPk" type="success"
                            @click="switchEnv(scope.row, prodPk)">
                            切换生产
                        </el-button>
                        <el-button type="danger" size="mini" @click="deleteRow(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination v-if="total > 0" :current-page.sync="query.page" :page-size.sync="query.pageSize"
                :total="total" @current-change="fetchList" @size-change="fetchList"
                style="margin:12px 0; text-align:center" />
        </el-card>

        <!-- 新增&编辑弹窗 -->
        <el-dialog :visible.sync="dialogVisible" :title="form.id ? '编辑配置' : '新增配置'" width="920px"
            :before-close="handleClose">
            <template slot="title">
                <span>
                    {{ form.id ? '编辑配置' : '新增配置' }}
                    <el-button v-if="!form.id" type="primary" size="mini" class="import-btn" :loading="importLoading"
                        @click="importLatestConfig">导入上个版本配置</el-button>
                </span>
            </template>
            <el-form :model="form" ref="form" :rules="rules" label-width="100px" label-position="left">

                <!-- 版本号配置 -->
                <div class="form-section">
                    <div class="section-title">版本配置</div>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="最低版本" prop="min_version">
                                <el-input v-model="form.min_version" placeholder="如：1.0.0" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="最高版本" prop="max_version">
                                <el-input v-model="form.max_version" placeholder="如：2.5.3" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <!-- 功能配置 -->
                <div class="form-section">
                    <div class="section-title">
                        功能配置
                        <span class="section-subtitle">（至少配置一个功能）</span>
                    </div>

                    <div class="feature-list">
                        <div v-for="(feature, featureIdx) in form.feature_list" :key="featureIdx" class="feature-card">

                            <!-- 功能头部 -->
                            <div class="feature-header">
                                <span class="feature-index">功能 {{ featureIdx + 1 }}</span>
                                <el-button v-if="form.feature_list.length > 1" size="mini" type="text"
                                    icon="el-icon-delete" class="delete-btn" @click="removeFeature(featureIdx)">
                                    删除功能
                                </el-button>
                            </div>

                            <!-- 功能名选择 -->
                            <el-form-item label="功能名称" :prop="`feature_list.${featureIdx}.featureName`"
                                :rules="[{ required: true, message: '请选择功能名称', trigger: 'change' }]">
                                <el-select v-model="feature.featureName" placeholder="请选择功能" filterable clearable
                                    style="width: 100%">
                                    <el-option v-for="item in featureNameOptions" :key="item.value" :label="item.label"
                                        :value="item.value" :disabled="featureNameIsSelected(item.value, featureIdx)" />
                                </el-select>
                            </el-form-item>

                            <!-- 模型组列表 -->
                            <div class="model-groups">
                                <div class="model-group-title">模型配置</div>

                                <div v-for="(mg, mgIdx) in feature.modelGroups" :key="mgIdx" class="model-group-card">

                                    <!-- 模型组头部 -->
                                    <div class="model-group-header">
                                        <span class="model-group-index">配置组 {{ mgIdx + 1 }}</span>
                                        <el-button v-if="feature.modelGroups.length > 1" size="mini" type="text"
                                            icon="el-icon-delete" class="delete-btn"
                                            @click="removeGroup(featureIdx, mgIdx)">
                                            删除组
                                        </el-button>
                                    </div>

                                    <!-- 模型选择 -->
                                    <el-form-item label="选择模型"
                                        :prop="`feature_list.${featureIdx}.modelGroups.${mgIdx}.models`"
                                        :rules="[{ required: true, message: '请至少选择一个模型', trigger: 'change' }]">
                                        <el-select v-model="mg.models" multiple filterable clearable style="width: 100%"
                                            placeholder="请选择模型">
                                            <el-option v-for="opt in modelOptions" :key="opt.value" :label="opt.label"
                                                :value="opt.value" />
                                        </el-select>
                                    </el-form-item>

                                    <!-- 提示词 -->
                                    <el-form-item label="提示词"
                                        :prop="`feature_list.${featureIdx}.modelGroups.${mgIdx}.prompt`"
                                        :rules="[{ required: true, message: '请输入提示词', trigger: 'blur' }]">
                                        <el-input v-model="mg.prompt" type="textarea" :rows="4"
                                            placeholder="请输入提示词内容..." show-word-limit :maxlength="1000"
                                            style="width: 100%" />
                                    </el-form-item>
                                </div>

                                <!-- 新增模型组按钮 -->
                                <div class="add-group-btn">
                                    <el-button size="small" type="primary" plain icon="el-icon-plus"
                                        @click="addGroup(featureIdx)">
                                        新增模型组
                                    </el-button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 新增功能按钮 -->
                    <div class="add-feature-btn">
                        <el-button type="primary" plain icon="el-icon-plus" @click="addFeature">
                            新增功能
                        </el-button>
                    </div>
                </div>
            </el-form>

            <!-- 底部按钮 -->
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" :loading="saveLoading" @click="handleSave">
                    {{ saveLoading ? '保存中...' : '确定保存' }}
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>


<script>
import axios from 'axios'
export default {
    data() {
        return {
            query: { version: '', page: 1, pageSize: 10 },
            list: [

            ],
            total: 0,
            loading: false,
            dialogVisible: false,
            saveLoading: false,
            form: {},
            prodPk: "com.trans.translationAiAndSubtitle",
            devPk: "com.TranslationAISubTitle",
            featureNameOptions: [
                { value: 'universal', label: '通用(未配置的功能兜底通用)' },
                { value: 'accurate_minute', label: '跨屏精翻' },
                { value: 'quick_translate_minute', label: '跨屏快翻' },
                { value: 'comic_realtime_minute', label: '漫画实时翻译' },
                { value: 'web_capture', label: '网页截图' },
                { value: 'quick_capture', label: '快捷截图' },
                { value: 'redeem_tokens', label: '网页翻译' },
                { value: 'float_copy', label: '悬浮复制屏翻' },
                { value: 'quick_text', label: '快捷文字屏翻' }
            ],
            modelOptions: [
                { value: "Qwen/Qwen2.5-32B-Instruct", label: "Qwen/Qwen2.5-32B-Instruct" },
                { value: "Qwen/Qwen2.5-14B-Instruct", label: "Qwen/Qwen2.5-14B-Instruct" },
                { value: "Qwen/Qwen2.5-7B-Instruct", label: "Qwen/Qwen2.5-7B-Instruct" },
                { value: "internlm/internlm2_5-7b-chat", label: "internlm/internlm2_5-7b-chat" },
                { value: "Qwen/Qwen2-7B-Instruct", label: "Qwen/Qwen2-7B-Instruct" },
                { value: "Pro/THUDM/gIm-4-9b-chat", label: "Pro/THUDM/gIm-4-9b-chat" },
                { value: "THUDM/glm-4-9b-chat", label: "THUDM/glm-4-9b-chat" },
                { value: "THUDM/GLM-4-32B-0414", label: "THUDM/GLM-4-32B-0414" },
                { value: "Pro/Qwen/Qwen2.5-VL-7B-Instruct", label: "Pro/Qwen/Qwen2.5-VL-7B-Instruct" },
                { value: "deepseek-ai/deepseek-vl2", label: "deepseek-ai/deepseek-vl2" },
                { value: "Qwen/Qwen2.5-VL-32B-Instruct", label: "Qwen/Qwen2.5-VL-32B-Instruct" },
            ],
            rules: {
                min_version: [
                    { required: true, message: '必填', trigger: 'blur' },
                    { pattern: /^\d+\.\d+\.\d+$/, message: '格式为1.0.0', trigger: 'blur' }
                ],
                max_version: [
                    { required: true, message: '必填', trigger: 'blur' },
                    { pattern: /^\d+\.\d+\.\d+$/, message: '格式为1.0.0', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        // 切换环境
        async switchEnv(row, targetPk) {
            this.$confirm(
                `确定将此配置切换到${this.envLabel(targetPk)}环境吗？`,
                "环境切换",
                { type: "warning" }
            ).then(async () => {
                // 你需要后端提供一个切换pk的接口，比如 /modelConfig/switchEnv
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Transir/modelConfig/switchEnv', {
                    id: row.id,
                    pk: targetPk
                });
                if (data.code === 0) {
                    this.$message.success('环境切换成功');
                    this.fetchList();
                } else {
                    this.$message.error(data.msg || '环境切换失败');
                }
            });
        },
        envLabel(pk) {
            if (pk === this.prodPk) return '生产';
            if (pk === this.devPk) return '开发';
            return pk || '未知';
        },
        handleClose(done) {
            this.dialogVisible = false;
            this.$nextTick(() => {
                if (this.$refs.form) this.$refs.form.clearValidate();
            });
            if (done) done();
        },
        featureNameLabel(val) {
            const it = this.featureNameOptions.find(i => i.value === val)
            return it ? it.label : val
        },
        // 如果你允许多个feature，以下辅助防止重复（也可省略！）
        featureNameIsSelected(val, idx) {
            const arr = this.form.feature_list.map(f => f.featureName);
            // 已选过且不是自己
            return arr.includes(val) && this.form.feature_list[idx]?.featureName !== val;
        },
        // 若只允许一个feature关联一种功能，这个返回false即可
        selectDisabled(idx) { return false },
        parseFeature(f) {
            if (!f) return []
            if (typeof f === 'string') try { return JSON.parse(f) } catch { return [] }
            return Array.isArray(f) ? f : []
        },
        async fetchList() {
            this.loading = true
            try {
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Transir/modelConfig/list', {
                    page: this.query.page,
                    pageSize: this.query.pageSize,
                    version: this.query.version
                })
                if (data.code === 0) {
                    // 解析feature_list
                    this.list = data.data.list.map(row => ({
                        ...row,
                        feature_list: this.parseFeature(row.feature_list)
                    }))
                    this.total = data.data.total
                } else this.$message.error(data.msg || '获取失败')
            } finally { this.loading = false }
        },
        resetQuery() {
            this.query.version = ''; this.query.page = 1; this.fetchList()
        },
        // 打开弹窗新增/编辑
        openDialog(row) {
            if (row) {
                // 编辑
                const feature_list = this.parseFeature(row.feature_list).map(f => ({
                    ...f,
                    modelGroups: (f.modelGroups || []).map(g => ({
                        ...g,
                        models: Array.isArray(g.models)
                            ? g.models
                            : (typeof g.models === 'string'
                                ? g.models.split(',').map(s => s.trim()).filter(Boolean)
                                : [])
                    }))
                }))
                this.form = {
                    id: row.id,
                    min_version: row.min_version,
                    max_version: row.max_version,
                    feature_list: feature_list.length ? feature_list : [this.defaultFeature()]
                }
            } else {
                // 新建
                this.form = {
                    min_version: '',
                    max_version: '',
                    feature_list: [this.defaultFeature()]
                }
            }
            this.dialogVisible = true
            this.$nextTick(() => {
                // form可能还没渲染，需要nextTick后操作
                this.$refs.form && this.$refs.form.clearValidate && this.$refs.form.clearValidate();
            })
        },


        defaultFeature() {
            return {
                featureName: '',
                modelGroups: [{ prompt: '', models: [] }]
            }
        },

        // 动态表单操作
        addFeature() {
            this.form.feature_list.push(this.defaultFeature())
        },
        removeFeature(idx) {
            if (this.form.feature_list.length <= 1) return
            this.form.feature_list.splice(idx, 1)
        },
        addGroup(fidx) {
            this.form.feature_list[fidx].modelGroups.push({ prompt: '', models: [] })
        },
        removeGroup(fidx, gidx) {
            if (this.form.feature_list[fidx].modelGroups.length <= 1) return
            this.form.feature_list[fidx].modelGroups.splice(gidx, 1)
        },
        // 保存
        async handleSave() {
            await this.$refs.form.validate()
            // modelGroups 里直接传 models 数组，别 split 什么字符串
            let feat = (this.form.feature_list || []).map(f => ({
                ...f,
                modelGroups: (f.modelGroups || []).map(g => ({
                    prompt: g.prompt,
                    models: Array.isArray(g.models) ? g.models : []
                }))
            }))
            if (!feat.length) return this.$message.warning('至少包含一个功能')
            this.saveLoading = true
            try {
                const params = {
                    ...this.form,
                    feature_list: JSON.stringify(feat),
                    status: 1
                }
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Transir/modelConfig/save', params)
                if (data.code === 0) {
                    this.$message.success('保存成功')
                    this.dialogVisible = false
                    this.fetchList()
                } else {
                    this.$message.error(data.msg || '保存失败')
                }
            } finally { this.saveLoading = false }
        },

        // 删除
        deleteRow(row) {
            this.$confirm('确定要删除此配置吗？', '提示', { type: 'warning' }).then(async () => {
                try {
                    const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Transir/modelConfig/delete', { id: row.id })
                    if (data.code === 0) {
                        this.$message.success('已删除')
                        this.fetchList()
                    } else this.$message.error(data.msg || '删除失败')
                } catch (err) { this.$message.error(err.msg || '删除失败') }
            })
        },
        async importLatestConfig() {
            this.importLoading = true;
            try {
                // 假设你list接口按id或者created_at倒序，查第一页1条就是最新的
                const { data } = await axios.post('https://xiaoshuchengzhang.com/node/Transir/modelConfig/list', {
                    page: 1,
                    pageSize: 1
                });
                if (data.code === 0 && data.data.list && data.data.list.length > 0) {
                    const latest = data.data.list[0];
                    // 拷贝并处理下，防止undefined
                    const feature_list = this.parseFeature(latest.feature_list).map(f => ({
                        ...f,
                        modelGroups: (f.modelGroups || []).map(g => ({
                            ...g,
                            models: Array.isArray(g.models)
                                ? g.models
                                : (typeof g.models === 'string'
                                    ? g.models.split(',').map(s => s.trim()).filter(Boolean)
                                    : [])
                        }))
                    }));
                    // 赋值到form，注意不赋id！
                    this.form = {
                        min_version: latest.min_version || '',
                        max_version: latest.max_version || '',
                        feature_list: feature_list.length ? feature_list : [this.defaultFeature()]
                    }
                    // 清除历史校验红框
                    this.$nextTick(() => {
                        if (this.$refs.form) this.$refs.form.clearValidate();
                    });
                    this.$message.success('已导入上个版本配置，请根据需要修改后保存！');
                } else {
                    this.$message.warning('没有可导入的上个版本配置！');
                }
            } catch (err) {
                this.$message.error('导入失败: ' + (err.msg || err.message));
            }
            this.importLoading = false;
        },
    },
    mounted() { this.fetchList() }
}
</script>


<style scoped>
.import-btn {
    margin-left: 20px;
    /* 标题和按钮之间加距 */
    vertical-align: middle;
}
/* 表单区域样式 */
.form-section {
    margin-bottom: 24px;
}

.form-section:last-child {
    margin-bottom: 0;
}

/* 区域标题 */
.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #409EFF;
    position: relative;
}

.section-subtitle {
    font-size: 12px;
    font-weight: 400;
    color: #909399;
    margin-left: 8px;
}

/* 功能卡片 */
.feature-list {
    margin-bottom: 16px;
}

.feature-card {
    background: #fafbfc;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 16px;
    transition: all 0.3s ease;
}

.feature-card:hover {
    border-color: #c6e2ff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.feature-card:last-child {
    margin-bottom: 0;
}

/* 功能头部 */
.feature-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
}

.feature-index {
    font-size: 14px;
    color: #409EFF;
}

/* 模型组相关 */
.model-groups {
    margin-top: 16px;
}

.model-group-title {
    font-size: 14px;
    font-weight: 500;
    color: #606266;
    margin-bottom: 12px;
}

.model-group-card {
    background: #ffffff;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    padding: 16px;
    margin-bottom: 12px;
    transition: border-color 0.3s ease;
}

.model-group-card:hover {
    border-color: #c6e2ff;
}

.model-group-card:last-child {
    margin-bottom: 0;
}

.model-group-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.model-group-index {
    font-size: 13px;
    color: #909399;
    font-weight: 500;
}

/* 删除按钮 */
.delete-btn {
    color: #f56c6c;
    padding: 0;
}

.delete-btn:hover {
    color: #f56c6c;
    background: transparent;
}

/* 新增按钮区域 */
.add-group-btn {
    text-align: center;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px dashed #dcdfe6;
}

.add-feature-btn {
    text-align: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px dashed #dcdfe6;
}

/* 底部按钮 */
.dialog-footer {
    text-align: right;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
}

/* 响应式调整 */
@media (max-width: 768px) {

    .feature-header,
    .model-group-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .delete-btn {
        align-self: flex-end;
    }
}

/* Element UI 组件样式微调 */
.el-form-item {
    margin-bottom: 18px;
}

.el-form-item:last-child {
    margin-bottom: 0;
}

.el-textarea__inner {
    font-family: inherit;
    line-height: 1.5;
}

.el-select .el-tag {
    margin-right: 4px;
}

/* 滚动条样式 */
.el-dialog__body {
    max-height: 70vh;
    overflow-y: auto;
}

.el-dialog__body::-webkit-scrollbar {
    width: 6px;
}

.el-dialog__body::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.el-dialog__body::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.el-dialog__body::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}
</style>